package com.feiyue.learning.product_service.listener;

import com.feiyue.learning.product_service.zk.RegisterService;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.net.InetAddress;
import java.util.Properties;

public class InitListener implements ServletContextListener {

    private static final String SERVER_PORT = "server.port";
    private static final String SERVICE_NAME = "spring.application.name";

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        try {

            // 加载配置文件
            Properties properties = new Properties();
            properties.load(InitListener.class.getClassLoader().getResourceAsStream("config/application.properties"));

            String hostAddress = InetAddress.getLocalHost().getHostAddress();
            int port = Integer.valueOf(properties.getProperty(SERVER_PORT));
            String serviceName = properties.getProperty(SERVICE_NAME);

            // 注册服务
            RegisterService.register(serviceName, hostAddress, port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
